package com.ycz.algorithm.utils.hash;

/**
 * @author yancz
 * @ClassName SimpleHashFunction
 * @description: 简单的哈希算法
 * @date 2024-12-17 17:17:14
 * @version: 1.0
 */
public class SimpleHashFunction {

    public static void main(String[] args) {
        System.out.println(addHash("yan"));
        System.out.println(addHash("cheng"));
        System.out.println(addHash("zhi"));
        System.out.println(mulHash("yan"));
        System.out.println(mulHash("cheng"));
        System.out.println(mulHash("zhi"));
        System.out.println(xorHash("yan"));
        System.out.println(xorHash("cheng"));
        System.out.println(xorHash("zhi"));
        System.out.println(rotHash("yan"));
        System.out.println(rotHash("cheng"));
        System.out.println(rotHash("zhi"));
    }

    // 加法哈希
    public static int addHash(String key) {
        long hash = 0;
        final int MODULES = 1000000007;
        for (char c : key.toCharArray()) {
            hash = (hash + (int) c) % MODULES;
        }
        return (int) hash;
    }

    // 乘法哈希
    public static int mulHash(String key) {
        long hash = 0;
        final int MODULES = 1000000007;
        for (char c : key.toCharArray()) {
            hash = (31 * hash + (int) c) % MODULES;
        }
        return (int) hash;
    }

    // 异或哈希
    public static int xorHash(String key) {
        int hash = 0;
        final int MODULES = 1000000007;
        for (char c : key.toCharArray()) {
            hash ^= (int) c;
        }
        return hash & MODULES;
    }

    // 旋转哈希
    public static int rotHash(String key) {
        long hash = 0;
        final int MUDULES = 1000000007;
        for (char c : key.toCharArray()) {
            hash = ((hash << 4) ^ (hash >> 28) ^ (int) c) % MUDULES;
        }
        return (int) hash;
    }

}
